<template>
  <div class="edit">
    <!-- 头部区域 -->
    <van-nav-bar title="编辑资料" left-arrow @click-left="onClickLeft" />
    <!-- 图片区域 -->
    <div class="img">
      <van-image
        width="100"
        height="100"
        round
        fit="cover"
        :src="myInfo.photo"
      />
       <!-- 编辑头像弹窗 -->
       <van-uploader class="myuploader" :after-read="afterRead" />
    </div>
   

    <!-- 其他信息 -->
    <van-cell-group>
      <van-cell
        title="名称"
        @click="openName(myInfo.name)"
        is-link
        :value="myInfo.name"
      />
      <van-cell
        title="性别"
        @click="openGender"
        is-link
        :value="myInfo.gender ? '女' : '男'"
      />
      <van-cell
        title="生日"
        @click="openBirth(myInfo.birthday)"
        is-link
        :value="myInfo.birthday"
      />
    </van-cell-group>
    <!-- 编辑名称弹窗 -->
    <van-dialog
      v-model="nameShow"
      title="修改名称"
      show-cancel-button
      @confirm="confirmName"
    >
      <van-field ref="myfield" v-model="myName" />
    </van-dialog>
    <!-- 编辑性别弹窗 -->
    <van-popup
      v-model="genderShow"
      position="bottom"
      :style="{ height: '25%' }"
    >
      <van-nav-bar
        title="修改性别"
        left-text="取消"
        @click-left="genderCancel"
      />
      <van-cell-group>
        <van-cell title="男" @click="changeGender(0)" is-link />
        <van-cell title="女" @click="changeGender(1)" is-link />
      </van-cell-group>
    </van-popup>
    <!-- 编辑生日弹窗 -->
    <van-popup v-model="birthShow" position="bottom" :style="{ height: '45%' }">
      <van-datetime-picker
        v-model="birthday"
        @confirm="comfirmBirth"
        type="date"
        title="选择年月日"
        :min-date="minDate"
        :max-date="maxDate"
      />
    </van-popup>
    <!-- 编辑裁剪弹窗 -->
    <div v-if="mypannelShow" class="mypannel">
      <vueCropper
        ref="cropper"
        :img="cropImg"
        autoCrop
        :autoCropWidth="150"
        :autoCropHeight="150"
      ></vueCropper>
      <van-button @click="cutImg" class="btnOne" type="primary">裁剪</van-button>
      <van-button class="btnTwo" type="primary">取消</van-button>
    </div>
  </div>
</template>

<script>
import { editUserInfoApi, uploadImgApi } from "@/api";
import moment from "moment";
import { VueCropper }  from 'vue-cropper' 

export default {
  // computed: {
  //     myInfo() {
  //         return this.$store.state.userInfo
  //     }
  // },
  data() {
    return {
      nameShow: false,
      myName: "",
      genderShow: false,
      // 控制生日面板的显示与隐藏
      birthShow: false,
      // 当前日期组件的时间
      birthday: new Date(),
      // 日期组件的开始时间
      minDate: new Date("2000-1-1"),
      // 日期组件的结束时间
      maxDate: new Date("2026-1-1"),
      mypannelShow: false,
      cropImg: '',
    };
  },
  computed: {
    myInfo: function () {
      return this.$store.state.userInfo;
    },
    

  },
  methods: {
    onClickLeft() {
      this.$router.push("/layout/my");
    },
    openName(name) {
      //打开面板
      this.nameShow = true;
      //输入框中输入默认值
      this.myName = name;
      //输入框获取焦点(但 vue 在加载 vant 中的组件采用的懒加载方式（使用时才会加载))
      //而渲染需要一定时间 不能立即调用 this.$refs.myfield.foucs()
      this.$nextTick(() => {
        this.$refs.myfield.focus();
      });
    },
    async confirmName() {
      await editUserInfoApi({
        name: this.myName,
      });
      this.$toast.success("修改用户信息成功");
      this.$store.commit("setUserInfo", {
        ...this.myInfo, // 先保存之前所有的数据
        name: this.myName, // 替换掉原数据中的 name 属性
      });
    },
    openGender() {
      this.genderShow = true;
    },
    genderCancel() {
      this.genderShow = false;
    },
    async changeGender(gender) {
      await editUserInfoApi({
        gender,
      });
      this.$toast.success("修改性别成功");
      this.$store.commit("setUserInfo", {
        ...this.myInfo, // 先保存之前所有的数据
        gender, // 替换掉原数据中的 gender 属性
      });
    },
    openBirth(birth) {
      this.birthShow = true;
      this.birthday = new Date(birth);
    },
    async comfirmBirth(value) {
      // 将时间对象使用 moment 转为字符串
      const mybirth = moment(value).format("YYYY-MM-DD");
      // 将时间提交到服务器
      await editUserInfoApi({
        birthday: mybirth,
      });
      // 提示修改成功
      this.$toast.success("修改日期成功");
      // 更新 vuex 中的数据
      this.$store.commit("setUserInfo", {
        ...this.myInfo, // 先保存之前所有的数据
        birthday: mybirth,
      });
      // 关闭面板
      this.birthShow = false;
    },
    afterRead(file) {
      this.mypannelShow = true
      // 将选中的图片内容保存为要裁剪的图片
      this.cropImg = file.content
    },
     // 点击左下角的裁剪按钮：开始裁剪图片
    cutImg() {
      this.$refs.cropper.getCropBlob(async (data) => {
        // 将图片存储到 FormDate 对象
        const fd = new FormData()
        fd.append("photo", data)
        // console.log(data); // data 就是裁剪后的图片
        const res = await uploadImgApi(fd)
        this.$toast.success("修改头像成功");
        // console.log(res);
         // 接收返回的图片
            const imgPath = res.data.data.photo;
            // 关闭面板
            this.mypannelShow = false;
            // 更新 vuex 中的数据
            this.$store.commit("setUserInfo", {
                ...this.myInfo, // 先保存之前所有的数据
                photo: imgPath,
            });
      });
    },
  },
  created() {
    this.$store.dispatch("setUserInfo");
  },
  components: {
    VueCropper,
  }
};
</script>

<style lang="less">
.edit {
  i.van-icon.van-icon-arrow-left.van-nav-bar__arrow {
    color: #fff;
  }
  .img {
    height: 120px;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    .myuploader {
      opacity: 0;
      position: absolute;
      .van-uploader__upload {
        width: 110px;
        height: 110px;
      }
    }
  }
  input.van-field__control {
    border: 1px solid #ccc;
    height: 40px;
    line-height: 40px;
    padding-left: 10px;
  }
  span.van-nav-bar__text {
    color: #fff;
  }
  .mypannel {
    width: 100vw;
    height: 100vh;
    background: red;
    position: fixed;
    top: 0;
    left: 0;
    .btnOne {
      position: absolute;
      left: 0;
      bottom: 0;
    }
    .btnTwo {
      position: absolute;
      right: 0;
      bottom: 0;
    }
  }
}
</style>